<template>
  <div id="show-add">
    <div class="back-bar">
      <el-button style="line-height:25px;"
                 @click="$router.go(-1)"
                 icon="el-icon-back"
                 type="text">返回</el-button>
    </div>

    <div class="left">
      <div class="head">
        <!-- <div class="iconbar"></div> -->
        <div class="head-text">演出组成</div>
      </div>
      <div style="padding:10px 5px;overflow: auto;height: calc(100% - 40px);">
        <el-input v-model="filterText"
                  placeholder="输入关键字进行过滤"
                  size="small" />
        <el-tree ref="tree"
                 draggable
                 :data="data"
                 style="margin-top:10px;"
                 node-key="id"
                 default-expand-all
                 :filter-node-method="filterNode"
                 :expand-on-click-node="false"
                 :allow-drop="handleAllowDrop"
                 :allow-drag="handleAllowDrag">
          <span slot-scope="{ node, data }"
                @click="handleTreeNodeClick(node)"
                class="custom-tree-node"
                :style="{backgroundColor: node.data.id===chosenNode?'rgba(64,158,255,.2)':''}">
            <span>
              <el-tag v-if="data.nodeType"
                      size="mini"
                      :type="data.nodeType==='篇章'?'':data.nodeType==='节目'?'success':'warning'">
                <!-- {{ programType.formatType(data.type) }} -->
                {{data.nodeType}}
              </el-tag>
              <!-- <el-tooltip :content="data.name || data.id"> -->
              <span :title="data.name || data.id">{{ data.name || data.id }}</span>
              <!-- </el-tooltip> -->
            </span>
            <!-- <span v-if="node.level <= 1">
              <el-button type="text"
                         size="mini"
                         @click="() => append(data)">
                新增
              </el-button>
              <el-button v-if="node.level !== 1"
                         type="text"
                         size="mini"
                         @click="() => remove(node, data)">
                删除
              </el-button>
            </span> -->
          </span>
        </el-tree>
      </div>
    </div>

    <div class="right">
      <div class="head">
        <div class="head-text">
          {{ chosenType === '演出'?'演出信息':chosenType === '篇章'?'篇章信息':chosenType === '节目'?'节目信息':'演出信息' }}
        </div>
      </div>

      <div class="container">
        <el-divider content-position="left">基本信息</el-divider>
        <el-button type="text"
                   class="head-button"
                   @click="handleEditClick(chosenType)"
                   icon="el-icon-edit">修改</el-button>
        <item-detail v-if="chosenType === '演出'"
                     :description="detailObj"
                     :columns="playColumns"></item-detail>
        <item-detail v-if="chosenType === '篇章'"
                     :description="sectionObj"
                     :columns="sectionColumns"></item-detail>
        <item-detail v-if="chosenType === '节目'"
                     :description="programObj"
                     :columns="programColumns"></item-detail>

        <div v-if="chosenNode">
          <el-divider v-if="chosenType === '演出'"
                      content-position="left">{{detailObj.category === 2?'篇章列表':'节目列表'}}</el-divider>
          <complex style="height:auto"
                   @handle-edit="handletabEdit"
                   :tableData="complexTabData"
                   :node="nodeObj"
                   :display.sync="comVisbile"
                   v-if="chosenType === '演出' && detailObj.category === 2" />
          <program-list style="height:auto"
                        @handle-edit="handletabEdit"
                        :tableData="complexTabData"
                        :node="nodeObj"
                        :display.sync="proVisbile"
                        v-if="chosenType === '演出' && detailObj.category === 1" />
        </div>

        <div v-if="chosenNode">
          <el-divider v-if="chosenType === '篇章'"
                      content-position="left">节目列表</el-divider>
          <program-list style="height:auto"
                        @handle-edit="handletabEdit"
                        :display.sync="proVisbile"
                        :node="nodeObj"
                        :tableData="programTabData"
                        v-if="chosenType === '篇章'" />
        </div>

        <div v-if="chosenNode">
          <el-divider v-if="chosenType === '节目'"
                      content-position="left">片段</el-divider>
          <part-list style="height:auto"
                     :display.sync="proVisbile"
                     :node="nodeObj"
                     :tableData="partTabData"
                     v-if="chosenType === '节目'" />
        </div>

        <div v-if="chosenNode">
          <el-divider content-position="left">人员名单</el-divider>
          <actorList style="height:auto"
                     :node="nodeObj"
                     :tableData="actorTabData"
                     :display.sync="actVisbile" />
        </div>
      </div>
    </div>

    <el-dialog :title="((chosenType === '节目' || tabEditType === '节目')?'节目':'篇章')+'新增/编辑'"
               width="450px"
               :visible.sync="visible">
      <el-form label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="addObj.name"></el-input>
        </el-form-item>
        <el-form-item label="类型"
                      v-if="chosenType === '节目' || tabEditType === '节目'">
          <el-select v-model="addObj.typeCode"
                     filterable
                     allow-create
                     default-first-option
                     style="width:100%;">
            <el-option v-for="p in programType.type"
                       :key="p.value"
                       :label="p.label"
                       :value="p.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时长">
          <el-input v-model="addObj.lenth"
                    maxlength="3"
                    oninput="if(isNaN(parseInt(value)))value=value.slice(0,0)"
                    placeholder="请输入整数分钟">
            <i slot="suffix">分钟</i></el-input>
        </el-form-item>
        <el-form-item label="起点时间">
          <el-input v-model="addObj.min"
                    style="width:49%"
                    maxlength="3"
                    @input="hanldeInput"
                    oninput="if(isNaN(parseInt(value)))value=value.slice(0,0)"
                    placeholder="请输入整数">
            <i slot="suffix">分</i></el-input>
          <el-input v-model="addObj.sec"
                    @input="inputSecondListen"
                    style="width:49%"
                    maxlength="2"
                    oninput="if(isNaN(parseInt(value)))value=value.slice(0,0)"
                    placeholder="请输入整数">
            <i slot="suffix">秒</i></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea"
                    :autosize="{ minRows: 3, maxRows: 5 }"
                    v-model="addObj.introduction"></el-input>
        </el-form-item>
        <el-form-item label="人员名单">
          <el-input type="textarea"
                    :autosize="{ minRows: 3, maxRows: 5 }"
                    v-model="addObj.extraActor"></el-input>
        </el-form-item>
        <div v-if="(0 === extraArray.length)"
             style="text-align:center">
          <el-button icon="el-icon-plus"
                     @click="addItem" />
        </div>

        <div style="margin-bottom:22px"
             v-for="(item,i) in extraArray"
             :key="item.id">
          <el-input style="width:80px;"
                    v-model="item.key"></el-input>
          <el-input style="width:calc(100% - 200px)"
                    v-model="item.value"></el-input>
          <el-button-group>
            <el-button v-if="(i === extraArray.length-1)"
                       icon="el-icon-plus"
                       @click="addItem"></el-button>
            <el-button icon="el-icon-minus"
                       @click="deleteItem(i)"></el-button>
          </el-button-group>
        </div>
        <el-row style="text-align:right">
          <el-button size="small"
                     @click="handleDialogSubmit"
                     type="primary">提交</el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import programList from './component/programList'
import actorList from './component/actorList'
import complex from './component/complex'
import itemDetail from './component/details'
import partList from './component/partList'
import API from '../../api/show'
import programType from '../../types/programType'

let id = 1000
export default {
  name: 'PlayDetail',
  components: { programList, actorList, complex, itemDetail, partList },
  data() {
    const data = []
    return {
      visible: false,
      extraArray: [
        {
          id: this.guid(),
          key: '',
          value: ''
        }
      ],

      nodeObj: {
        nodeId: '',
        category: ''
      },
      programType: programType,
      id: '',
      comVisbile: false,
      actVisbile: false,
      proVisbile: false,
      chosenData: null,
      addObj: {
        sec: null,
        min: null
      },
      chosenType: '演出',
      chosenNode: '',
      data: JSON.parse(JSON.stringify(data)),
      filterText: '',
      tableData: [],
      pagination: {
        page: 1,
        size: 10,
        total: 100
      },
      searchText: '',
      playColumns: [
        // {
        //   label: '总导演：',
        //   name: 'director',
        //   width: '50%'
        // },
        // {
        //   label: '总策划：',
        //   name: 'brain',
        //   width: '50%'
        // },
        {
          label: '名称：',
          name: 'name',
          width: '50%'
        },
        {
          label: '类型：',
          name: 'type',
          width: '50%'
        },
        {
          label: '时间：',
          name: 'time',
          width: '50%'
        },
        {
          label: '时长：',
          name: 'lenth',
          width: '50%'
        },
        {
          label: '地点：',
          name: 'address',
          width: '50%'
        },
        {
          label: '播放链接：',
          name: 'videoUrl',
          width: '100%'
        },
        {
          label: '节目单：',
          name: 'imgsBill',
          width: '100%'
        },
        {
          label: '其他：',
          name: 'extra',
          width: '100%'
        }
      ],
      sectionColumns: [
        // {
        //   label: '序号：',
        //   name: 'number',
        //   width: '50%'
        // },
        {
          label: '名称：',
          name: 'name',
          width: '50%'
        },
        // {
        //   label: '类型：',
        //   name: 'type',
        //   width: '50%'
        // },
        {
          label: '时长：',
          name: 'lenth',
          width: '50%'
        },
        {
          label: '简介：',
          name: 'introduction',
          width: '100%'
        },
        // {
        //   label: '人员名单：',
        //   name: 'extraActor',
        //   width: '100%'
        // },
        {
          label: '其他：',
          name: 'extra',
          width: '100%'
        }
      ],
      programColumns: [
        // {
        //   label: '序号：',
        //   name: 'number',
        //   width: '50%'
        // },
        {
          label: '名称：',
          name: 'name',
          width: '50%'
        },
        {
          label: '类型：',
          name: 'type',
          width: '50%'
        },
        {
          label: '时长：',
          name: 'lenth',
          width: '50%'
        },
        {
          label: '简介：',
          name: 'introduction',
          width: '100%'
        },
        // {
        //   label: '人员名单：',
        //   name: 'extraActor',
        //   width: '100%'
        // },
        {
          label: '其他：',
          name: 'extra',
          width: '100%'
        }
      ],
      detailObj: {},
      sectionObj: {},
      programObj: {},
      actorTabData: [],
      complexTabData: [],
      programTabData: [],
      partTabData: [],
      tabEditType: ''
    }
  },
  computed: {
    totalSecond: {
      set(val) { },
      get() {
        const min = this.addObj.min ? this.addObj.min * 60 : 0
        const sec = this.addObj.sec || 0
        const startTime = parseInt(min) + parseInt(sec)
        return startTime
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.id = this.$route.query.id
    this.queryById(this.$route.query.id)
  },
  methods: {
    hanldeInput(event) {
      this.$forceUpdate()
    },
    inputSecondListen(event) {
      var number = this.addObj.sec
      if (number >= 60) {
        this.addObj.sec = 59;
      }
      this.hanldeInput()
    },
    guid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0
        const v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16);
      });
    },
    addItem() {
      const uuid = this.guid()
      this.extraArray.push({ id: uuid, name: '', value: '' })
    },
    deleteItem(i) {
      this.extraArray.splice(i, 1)
    },
    handleEditClick(chosenType) {
      switch (chosenType) {
        case '演出': {
          this.$router.push({
            path: 'basic',
            query: { id: this.id }
          })
          break
        }
        case '篇章': {
          this.visible = true
          this.addObj = { ...this.sectionObj }
          this.tabEditType = '篇章'
          break
        }
        case '节目': {
          this.visible = true
          this.addObj = { ...this.programObj }
          this.addObj.typeCode = this.addObj.typeCode ? this.addObj.typeCode : this.addObj.type
          this.addObj.min = Math.floor(this.addObj.startTime / 60)
          this.addObj.sec = this.addObj.startTime % 60
          this.tabEditType = '节目'
          break
        }
      }
    },
    handleTreeNodeClick(node) {
      console.log(node)
      this.nodeObj.nodeId = node.data.id
      this.chosenNode = node.data.id
      this.chosenType = node.data.nodeType
      this.queryActorByNodeId(node)
      if (this.chosenType === '演出') {
        this.nodeObj.category = 1
        this.queryComplexByNodeID(node)
      } else if (this.chosenType === '篇章') {
        this.nodeObj.category = 2
        this.queryProgramByNodeID(node)
        this.getSectionDetail()
      } else if (this.chosenType === '节目') {
        this.nodeObj.category = 3
        this.queryPartByNodeId(node)
        this.getProgramDetail()
      }
    },
    append(data) {
      this.chosenData = data;
      this.visible = true
    },
    remove(node, data) {
      console.log(node)
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      children.splice(index, 1)
    },

    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleSizeChange(v) { },
    handleCurrentChange(v) { },
    handleSubmit() {
      const newChild = { id: id++, label: this.addObj.name, children: [], type: this.addObj.type }
      if (!this.chosenData.children) {
        this.$set(this.chosenData, 'children', [])
      }
      this.chosenData.children.push(newChild)
      this.visible = false
      this.addObj.name = ''
      this.addObj.type = '篇章'
      this.addObj.des = ''
    },
    queryById(id = this.$route.query.id) {
      API.getPlayById(id).then(res => {
        this.data = [res.data]
        if (res.data.extra && res.data.extra.length > 0) {
          this.extraArray = res.data.extra.map(e => {
            return {
              id: e.id || this.guid(),
              key: e.key,
              value: e.value
            }
          })
        } else {
          this.extraArray = res.data.extra || []
        }

        this.detailObj = Object.assign({}, this.detailObj, res.data)
        this.detailObj.type = this.formatPlayType(this.detailObj.typeCode)
        this.detailObj.extra = this.detailObj.extra || []
        this.detailObj.imgsBills = this.detailObj.imgsBills || []
        // this.detailObj.extra = this.formatExtraArray(this.detailObj.extra)
      })
    },
    formatPlayType(type) {
      switch (type) {
        case 1: {
          return '综合'
        }
        case 2: {
          return '春节团拜会'
        }
        case 3: {
          return '新年茶话会'
        }
        case 4: {
          return '新年戏曲晚会'
        }
        default: return type
      }
    },
    formatExtraArray(arr) {
      if (!arr) return ''
      return arr.map(a => {
        return a.key + '：' + a.value
      }).join('，')
    },
    formatAllType(node) {
      const type = node.data.typeCode || node.data.type
      // if (!type && this.detailObj.category === 1) return '节目'
      if (type <= 14) return '演出'
      else if (type > 14 && type <= 25) return '篇章'
      else if (type > 25) return '节目'
    },
    queryActorByNodeId(node) {
      API.queryActorByNodeId(this.nodeObj).then(res => {
        this.actorTabData = res.data.items || []
      })
    },
    queryComplexByNodeID(node) {
      console.log(456)
      API.querySectionByNodeId({
        playId: node.data.id
        // category: this.chosenType === '演出' ? 1 : this.chosenType === '篇章' ? 2 : 3
      }).then(res => {
        this.complexTabData = res.data.items || []
      })
    },
    queryProgramByNodeID(node) {
      API.queryProgramBySectionId({
        sectionId: node.data.id
        // category: this.chosenType === '演出' ? 1 : this.chosenType === '篇章' ? 2 : 3
      }).then(res => {
        this.programTabData = res.data.items || []
      })
    },
    queryPartByNodeId(node) {
      API.queryPartByNodeId({
        programId: node.data.id
        // category: this.chosenType === '演出' ? 1 : this.chosenType === '篇章' ? 2 : 3
      }).then(res => {
        this.partTabData = res.data.items || []
      })
    },
    getSectionDetail() {
      API.getSectionDetail(this.nodeObj.nodeId).then(res => {
        this.sectionObj = res.data
        this.extraArray = res.data.extra || []
        this.sectionObj.extraText = this.formatExtraArray(this.sectionObj.extra)
      })
    },
    getProgramDetail() {
      API.getProgramDetail(this.nodeObj.nodeId).then(res => {
        this.programObj = res.data
        this.extraArray = res.data.extra || []
        this.programObj.extraText = this.formatExtraArray(this.programObj.extra)
      })
    },
    handleDialogSubmit() {
      const param = {
        ...this.addObj,
        extra: this.extraArray,
        startTime: this.totalSecond
      }
      if ((this.nodeObj.category === 2 && this.tabEditType !== '节目') || this.tabEditType === '篇章') {
        // console.log(321)
        API.updateSection(param).then(res => { // 更新篇章基本信息
          this.visible = false
          this.queryById() // 更新树
          if (this.nodeObj.category !== 2) { // 演出篇章表格关联修改 更新篇章表格
            this.queryComplexByNodeID({ data: { id: this.nodeObj.nodeId } })
          } else { // 更新篇章基本信息展示
            this.getSectionDetail()
          }
        })
      } else if (this.nodeObj.category === 3 || this.tabEditType === '节目') {
        console.log(123)
        API.updateProgram(param).then(res => {
          this.visible = false
          this.queryById() // 更新树
          if (this.nodeObj.category === 3) {
            this.getProgramDetail() // 由树节点点击更新节目基本信息 
          } else if (this.tabEditType === '节目') {
            if (this.tabEditType === '节目' && this.nodeObj.category !== 2) { // 点击树节点演出为节目型 更新关联节目表
              this.queryComplexByNodeID({ data: { id: this.nodeObj.nodeId } })
            }
            if (this.tabEditType === '节目' && this.nodeObj.category === 2) { // 篇章关联的节目表格 更新节目关联表
              this.queryProgramByNodeID({ data: { id: this.nodeObj.nodeId } })
            }
          }
        })
      }
    },
    handletabEdit(obj) {
      console.log(obj)
      // this.addObj.min = obj.data.startTime ? Math.floor(obj.data.startTime / 60) : 0
      // this.addObj.sec = obj.data.startTime ? obj.data.startTime % 60 : 0
      this.tabEditType = obj.type
      if (obj.type === '节目') {
        // this.programObj = obj.data
        this.addObj = { ...obj.data }
        this.addObj.typeCode = obj.data.typeCode ? obj.data.typeCode : obj.data.type
        this.extraArray = obj.data.extra || []
      } else if (obj.type === '篇章') {
        // this.sectionObj = obj.data
        this.addObj = { ...obj.data }
        this.extraArray = obj.data.extra || []
      }
      this.visible = true
    },
    handleAllowDrop(draggingNode, dropNode, type) {
      // console.log(draggingNode, dropNode, type)
      return draggingNode.data.nodeType === dropNode.data.nodeType && type !== 'inner' && draggingNode.data.id === dropNode.data.id
    },
    handleAllowDrag(node) {
      console.log(node)
      return node.data.nodeType !== '演出'
    }
  }

}
</script>

<style lang="scss" scoped>
#show-add {
  width: 100%;
  height: calc(100vh - 50px);
  padding: 15px;
  // overflow: auto;
  .back-bar {
    // position: absolute;
    margin-top: -15px;
    left: 15px;
    top: 0;
  }
  .left {
    width: 300px;
    height: calc(100% - 30px);
    border: 1px solid #ccc;
    border-radius: 4px;
    float: left;
    // margin-top: 30px;
    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
    }
  }
  .right {
    width: calc(100% - 310px);
    height: calc(100% - 30px);
    border: 1px solid #ccc;
    border-radius: 4px;
    float: left;
    margin-left: 10px;
    // overflow: auto;
    // margin-top: 30px;
    // padding: 5px;

    header {
      margin-top: 5px;
      width: 100%;
      display: flex;
      flex-flow: row nowrap;
      justify-content: space-between;
      .inner-left {
        display: flex;
        justify-content: flex-start;
        align-items: center;
      }
    }
    main {
      padding: 10px 0;
    }
    footer {
      text-align: right;
    }
  }
  .head {
    width: 100%;
    height: 40px;
    position: relative;
    padding: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    z-index: 1;
    .head-text {
      font-weight: 600;
    }
  }
  .container {
    position: relative;
    .head-button {
      position: absolute;
      right: 10px;
      top: 30px;
    }
    width: 100%;
    height: calc(100% - 40px);
    overflow: auto;
  }
  /deep/ .table-header {
    padding: 0 6px;
  }
  /deep/ .el-table td,
  .el-table th {
    padding: 0;
  }
  /deep/ .el-table .cell,
  .el-table th div {
    padding: 6px 0;
  }
  /deep/ .el-dialog__body {
    padding: 10px 20px;
  }
  /deep/ .el-tree-node > .el-tree-node__children {
    overflow: unset;
  }
  /deep/ .el-divider__text {
    font-weight: 600;
    font-size: 16px;
  }
}
</style>
